const webpackMerge = require('webpack-merge');
const baseConfig = require('./webpack.base');
const TerserPlugin = require('terser-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const config = {
    mode: 'production',
    cache: {
        type: 'filesystem',
        buildDependencies: {
            config: [__filename],
        },
    },
    output: {
        asyncChunks: true,
        pathinfo: false, //优化
    },
    plugins: [
        new BundleAnalyzerPlugin(),
    ],
    module: {
        noParse: [/react\.min\.js$/], // 忽略对`react.min.js`文件的递归解析处理
    },
    optimization: {
        minimize: true, //开启压缩
        runtimeChunk: true,
        moduleIds: 'deterministic', //单独模块id，模块内容变化再更新
        splitChunks: {
            chunks: 'all', // 匹配的块的类型：initial（初始块），async（按需加载的异步块），all（所有块）
            automaticNameDelimiter: '~',
            cacheGroups: {
                // 项目第三方组件
                vendor: {
                    // name: 'vendors',
                    chunks: "all",
                    enforce: true, // 告诉 webpack 忽略 splitChunks.minSize、splitChunks.minChunks、splitChunks.maxAsyncRequests 和 splitChunks.maxInitialRequests 选项，并始终为此缓存组创建 chunk
                    test: /[\\/]node_modules[\\/]/,
                    priority: 10,
                },
                // 项目公共组件
                default: {
                    minSize: 0, // 分离后的最小块文件大小默认3000
                    name: 'common', // 用以控制分离后代码块的命名
                    minChunks: 3, // 最小共用次数
                    priority: 10, // 优先级，多个分组冲突时决定把代码放在哪块
                    reuseExistingChunk: true,
                },
            },
        },
        minimizer: [
            new TerserPlugin({
                extractComments: false, //不将注释提取到单独的文件中
                parallel: 4,
                terserOptions: {
                    parse: {
                        ecma: 8,
                    },
                    compress: {
                        ecma: 5,
                        warnings: false,
                        comparisons: false,
                        inline: 2,
                    },
                    mangle: {
                        safari10: true,
                    },
                    output: {
                        ecma: 5,
                        comments: false,
                        ascii_only: true,
                    },
                },
            }),
        ],
    },
};

const mergedConfig = webpackMerge.merge(baseConfig, config);

module.exports = mergedConfig;
